import React, { Component } from 'react'
import { Card, Input, Icon, Button, Spin, message } from 'antd'
import { history } from 'umi'
import './index.css'
import { login } from '@/services/admin'
export default class Login extends Component {
  state = {
    username: '',
    password: '',
    isLoading: false,
  }
  checkLogin = async () => {
    this.setState({ isLoading: true })
    const { username, password } = this.state
    if (!username || !password) {
      message.destroy()
      message.error('用户名和密码不能为空!')
      setTimeout(() => {
        this.setState({ isLoading: false })
      }, 500)
      return false
    }

    const res = await login(username, password)

    if (res.status === 200) {
      sessionStorage.setItem('token', res.token)
    } else {
      setTimeout(() => {
        this.setState({ isLoading: false })
      }, 500)
      return false
    }

    history.push('/admin')
  }
  render() {
    return (
      <div className="login-div">
        <Spin tip="Loading..." spinning={this.state.isLoading}>
          <Card title="博客系统" bordered style={{ width: '500', textAlign: 'center' }}>
            <Input
              id="username"
              size="large"
              allowClear
              placeholder="请输入用户名"
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              onChange={(e) => this.setState({ username: e.target.value })}
            />
            <br />
            <br />
            <Input.Password
              id="password"
              size="large"
              allowClear
              placeholder="请输入密码"
              prefix={<Icon type="key" style={{ color: 'rgba(0,0,0,.25)' }} />}
              onChange={(e) => this.setState({ password: e.target.value })}
            />
            <br />
            <br />
            <Button type="primary" size="large" block onClick={this.checkLogin}>
              登录
            </Button>
          </Card>
        </Spin>
      </div>
    )
  }
}
